package logic

import (
	"fmt"
	"math/rand"
	"strconv"
	"strings"
	"time"

	"gitee.com/firewing_group/configenv"
	"gitee.com/firewing_group/model/ctxdata"
	"gitee.com/firewing_group/model/model/stadvertisement"
	"gitee.com/firewing_group/model/model/stuser"
)

func LookedAide(cc *ctxdata.Cusctx, user *stuser.KuaiMaoUser, _index string) *stadvertisement.Advertisement {
	// 该组广告的第几个
	lastAd := stadvertisement.GetLastAds(cc, 2, user.UserName)
	if lastAd == nil {
		err := fmt.Errorf("%s", "找不到最近的广告记录")
		cc.Errf("err_%v", err)
		return nil
	} else {
		cc.Logf("第轮_%v", lastAd.Number)
		if lastAd.Inform[_index].LookTime != 0 {
			return lastAd
		}
	}
	// keth 奖励的权重数组
	var totalWeight int = 0
	weightInts, kethInts := func() ([]int, []int) {
		// 1000_250000/120_600000/25_1000000/5_1500000/1_2500000
		segs := strings.Split(configenv.GetEnv("weightsandreward"), "/")
		// var wlist,klist []int
		wlist := make([]int, len(segs))
		klist := make([]int, len(segs))
		for idx, v := range segs {
			tegs := strings.Split(v, "_")
			wlist[idx], _ = strconv.Atoi(tegs[0])
			klist[idx], _ = strconv.Atoi(tegs[1])
			totalWeight += wlist[idx]
		}
		return wlist, klist
	}()

	//随机数
	rand.Seed(time.Now().UnixNano())
	x := rand.Intn(totalWeight)
	y := 0
	var result int
	for idx, j := range weightInts {
		if x < (y + j) {
			result = kethInts[idx]
			break
		} else {
			//不在该权重，奖励＋1，判断在不在下一权重范围
			// result += 500000
			y += j
		}
	}

	//判断是不是翻倍
	money := int64(result)
	//更新纪录，并插入奖励金额
	lastAd.Inform[_index].Money = money
	lastAd.Inform[_index].LookTime = time.Now().Unix()
	lastAd.UpdateAdLooked(cc, _index)
	return lastAd
}

func ClickAide(cc *ctxdata.Cusctx, user *stuser.KuaiMaoUser, indexStr string) *stadvertisement.Advertisement {

	lastAd := stadvertisement.GetLastAds(cc, 2, user.UserName)
	if lastAd == nil {
		err := fmt.Errorf("%s", "找不到最近的广告记录")
		cc.Errf("err_%v", err)
		return nil
	} else {
		cc.Logf("第轮_%v", lastAd.Number)
		if lastAd.Inform[indexStr].ClickTime != 0 {
			return lastAd
		}
	}
	lastAd.Inform[indexStr].ClickTime = time.Now().Unix()
	err := lastAd.UpdateAdClicked(cc, indexStr)
	if err != nil {
		cc.Errf("clickaide_mongo_err_%v", err.Error())
	}
	return lastAd
}
